<?php

namespace app\api\service;

use app\model\DmjPlatformUsers;
use app\model\DmjUsers;
use app\model\OilAuth;

class DmjUserService extends CommonService
{
    /*
     用户注册或者登录 并返回用户信息
     用户注册一般有两种
     1，是手机号，这类先从 dmj_users 处理
     2，类似微信，先从platform 查询用户信息 然后再入库 dmj_users
     $userInfo todo 用户拓展用户其他信息 ，目前只是用手机号做登录或者注册此时是没有昵称等信息
    */
    public function byMobile($mobile, $appId, $platform, $userInfo = null)
    {
        $user = DmjUsers::with(['platform' => function ($query) use ($appId,$platform) {
            $query->where('app_id', $appId)->where('platform', $platform);
        }])->where('mobile', $mobile)->find();

        $errMsg = '';
        $isNew = 1; // 新用户
        if (!$user) {
            $user = new DmjUsers();
            if ($user->save(['mobile' => $mobile])) {
                $platformUser = [
                    'mobile' => $mobile,
                    'platform' => $platform,
                    'app_id' => $appId,
                ];
                if (!$user->platform()->save($platformUser)) {
                    $errMsg = '操作失败，请重试或者';
                }
            } else {
                // 返回失败
                $errMsg = '操作失败，请重试或者';
            }
        } else { // 平台用户存在
            if (($user->platform)->isEmpty()) {
                $platformUser = [
                    'mobile' => $mobile,
                    'platform' => $platform,
                    'app_id' => $appId,
                ];
                if (!$user->platform()->save($platformUser)) {
                    $errMsg = '操作失败，请重试或者';
                }
            } else {
                $isNew = 0;

                // 加油平台特殊处理 判断 platform 表的id是不是最新的，即：之后该用户是否再次注册其他渠道
                $lastestUser = DmjPlatformUsers::where('user_id', $user->id)->where('id', '>', $user->platform[0]->id)->find();
                if ($lastestUser) {
                    $isNew = 1;
                    $platformUser = $user->platform[0]->toArray();
                    unset($platformUser['id'],$platformUser['created_at'],$platformUser['updated_at']);
                    if (!$user->platform()->save($platformUser)) {
                        $errMsg = '操作失败，请重试或者';
                    } else {
                        DmjPlatformUsers::destroy($user->platform[0]->id);
                    }
                }
                // 加油平台特殊处理 结束
            }
        }

        if ($errMsg) {
            return $this->inValiReturn($errMsg);
        }

        if ($isNew) { // 新建用户的话从数据库再查询一次用于存储session
            $user = DmjUsers::with(['platform' => function ($query) use ($appId,$platform) {
                $query->where('app_id', $appId)->where('platform', $platform);
            }])->where('mobile', $mobile)->find();
        }

        //halt($user);

        $user->hidden(['deleted_at', 'updated_at', 'created_at', 'platform.deleted_at']);
        $user = $user->toArray();
        $user['platform'] = $user['platform'][0];

        return $this->valiReturn($user);
    }

    /**
     * 通过验证码登录 此时只是登录没有注册.
     */
    public function byCode($authCode)
    {
        $authInfo = OilAuth::where('code', $authCode)
            ->where('expired_at', '>', date('Y-m-d H:i:s'))
            ->where('try_times', '<', 2)->find();

        if ($authInfo) {
            ++$authInfo->try_times;
            $authInfo->save();
            $userInfo = DmjPlatformUsers::find($authInfo['related_id']);
            if ($userInfo) {
                $sessUser = DmjUsers::find($userInfo->user_id);
                $sessUser->hidden(['deleted_at', 'updated_at', 'created_at']);
                $userInfo->hidden(['deleted_at']);

                $sessUser = $sessUser->toArray();
                $sessUser['platform'] = $userInfo->toArray();

                return $this->valiReturn($sessUser);
            }
        } else {
            return $this->inValiReturn('登录超时，请重新登录');
        }
    }

    /*
     滴滴加油用户登录
    */
    public function oilUserLogin($mobile, $appId, $platform, $token, $userInfo = null)
    {
        $user = $this->byMobile($mobile, $appId, $platform, $userInfo);
        if ($user['code']) {
            return $this->inValiReturn('请先登录', 401);
        } else {
            $this->oilUserCache($token, $user['data']);
            // session('dmjuser', $user['data']);
        }

        return $this->valiReturn($user['data']);
    }

    /*
     用户会话信息缓存
     userinfo为空的时候返回token对应的用户信息
    */
    public function oilUserCache($token = '', $userinfo = null)
    {
        if ($userinfo) {
            return cache($token, $userinfo, 7200);
        }

        return  cache($token);
    }
}
